package movieGandalf.DB;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;

public class DescriptionsReader implements DataReader{
	
	public int read(Connection conn, InputStream in){
		String line = null;
		
		String imdbName = null;
		BigInteger movieID = null;
		String description = null;
		
		try{
			PreparedStatement stmt = conn.prepareStatement(new String("REPLACE INTO MovieDescriptions (movieID,description) VALUES (?,?)"));
			
			boolean isBegin = true;
			boolean isFirstRow = true;
			
			while ((line = MovieTools.getLine(in)) != null){
				int len = line.length();
				
				if (isBegin){
					if ((len<3 || !line.subSequence(0, 3).equals("===")))
						continue;
					else{
						isBegin = false;
						continue;
					}
				}
				
				if (len<5 || !line.substring(0,4).equals("MV: ") || line.charAt(4)=='"')
					continue;
				
				line = line.substring(4,len).trim()+"\t";
				imdbName = MovieTools.getIMDBName(line);
				movieID = MovieTools.getMovieID(conn, imdbName);
				if (movieID == null)
					continue;
				
				description = "";
				isFirstRow = true;
				
				while ((line = MovieTools.getLine(in)) != null){
					len = line.length();
					
					if ((len>=3 && line.subSequence(0, 3).equals("---")))
						break;
					
					if (len<4 || !line.substring(0,4).equals("PL: "))
						continue;
					
					if (isFirstRow)
						isFirstRow = false;
					else
						description += " ";
					description += line.substring(4,len);
				}
				if (description.equals(""))
					continue;
				
				stmt.setObject(1, movieID);
				stmt.setObject(2, description);
				stmt.addBatch();
			}
			
			stmt.executeBatch();
			conn.commit();
			stmt.close();
		}
		
		catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			try{
				in.close();
			}
			catch(Exception e){
				return 0;
			}
		}
		
		return 1;
	}
	
}
